<template>
  <div style="width: 100%;">
    <!-- 自选股票card -->
    <el-card class="stock-management-container">
      <div slot="header">
        <span class="header-title">自选股票</span>
      </div>
      <div class="filter"
        style="margin-top:20px;width:100%;display:flex;justify-content:space-between;align-items: center;">
        <el-input v-model="searchQuery" placeholder="输入股票代码或者股票名称" prefix-icon="el-icon-search" style="width:30%" />
        <el-button type="primary" @click="addMyStock">添加股票</el-button>
      </div>

      <!-- 自选股列表 -->
      <el-table :data="filteredStocks" :row-style='rowStyle' @row-click="ToStockMessagePage" stripe border v-model:empty-text="emptyMessage">
        <el-table-column label="股票名称" prop="name"></el-table-column>
        <el-table-column label="股票代码" prop="ts_code"></el-table-column>
        <el-table-column label="交易时间" prop="date"></el-table-column>
        <el-table-column label="现价" prop="price">
          <template #default="scope">
            <span v-if="scope.row.status === 'up'" style="color: red;">{{ scope.row.price }}</span>
            <span v-else-if="scope.row.status === 'down'" style="color: green;">{{ scope.row.price }}</span>
            <!-- 可添加更多条件判断 -->
            <span v-else>{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column label="涨跌额">
          <template #default="scope">
            <span v-if="scope.row.status === 'up'" style="color: red;">{{ formatRatio(scope.row) }}</span>
            <span v-else-if="scope.row.status === 'down'" style="color: green;">{{ formatRatio(scope.row) }}</span>
            <!-- 可添加更多条件判断 -->
            <span v-else>{{ formatRatio(scope.row) }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="开盘价" prop="open"></el-table-column>
      <el-table-column label="昨收价" prop="pre_close"></el-table-column> -->
        <el-table-column label="最高价" prop="high"></el-table-column>
        <el-table-column label="最低价" prop="low"></el-table-column>

        <!-- <el-table-column label="增长值" prop="increase"></el-table-column>
        <el-table-column label="成交金额" prop="amount"></el-table-column> -->
        <el-table-column label="成交量" prop="volume" :formatter="formatVolume"></el-table-column>
        <el-table-column label="操作" width="130">
          <template #default="scope">
            <div style="display: flex">
              <el-button type="primary" size="small" @click="ToStockMessagePage(scope.row)">查看</el-button>
              <el-button type="danger" size="small" @click="removeWatchlist(scope.row.id)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
    </el-card>

    <!-- 自选相关新闻card -->
    <el-card class="newslist-container" style="margin-top: 20px;">
      <div class="header-title">自选新闻</div>
      <div class="newsli" v-for="(item, index) in selectNews" :key="index" @click="ToContent(item.id)">
        <div class="newsTop">
          <div class="goodge" v-if="item.sentiment === 'positive'">利好</div>
          <div class="badge" v-else-if="item.sentiment === 'negative'">利空</div>
          <div class="unknownge" v-else>未知</div>
          <div>
            <h3 class="news_title"
                :style="{'color':getHasCheckedJournalism(item.id)?'#969696':'black'}"
                @click="ToJournalismPage(item.id)"
            >{{ item.title }}</h3>
            <div class="newsMessage">
              <div style="margin-left: 0">{{item.stockCode}}</div>
              <div style="margin-left: 0">{{item.stockName}}</div>
              <div>{{item.newsType}}</div>
              <div>{{item.originName}}</div>
              <div>{{item.publishDate}}</div>
            </div>
          </div>
        </div>
        <div style="display: flex">
          <div
              :style="{'text-indent':item.content.length > 34 ? '2em' : '',
              'color':getHasCheckedJournalism(item.id)?'#555454':'black'}"
              class="news_content"
              @click="ToJournalismPage(item.id)"
          >{{ item.content }}</div>
          <div>
            <img @click="ToJournalismPage(item.id)" v-if="item.imageSrc!==null" class="news_img" :src="item.imageSrc" alt="">
            <div v-if="item.imageSrc===null" class="news_img"></div>
          </div>
        </div>
      </div>
      <el-pagination @change="getWatchNews" :page-size="pageParams.pageSize" background v-model:current-page="pageParams.page"
        layout="prev, pager, next" :total="pageParams.total" />
    </el-card>

    <!-- 添加自选股对话框 -->
    <el-dialog v-model="dialogVisible" title="输入要添加的自选股信息">
      <el-form>
        <el-form-item>
          <el-input v-model="inputTsCode" placeholder="请输入股票代码"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addSelect">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 导入所需模块
import {onMounted, ref, computed, reactive, watch} from 'vue';
import { ElMessage,ElMessageBox  } from 'element-plus';
import { useCounterStore } from "@/stores/counter.js";
import { getKlineDataApi, getStockRealDataApi } from '@/api/tushare';
import { getWatchlistApi,addWatchlistApi,removeWatchlistApi ,getSelectNewsApi} from '@/api/watchlist';
import {listThreeNewsApi} from "@/api/request"
import {useRouter} from "vue-router";
import router from "@/router/index.js";


const Router=useRouter()
const searchQuery = ref("");
// 用户自选股票
const stocks = ref([]);
const store = useCounterStore()
const userMessage = ref(store.UserMessage)
// 自选新闻列表
const selectNews = ref([])
// 是否展开添加自选股对话框
const dialogVisible = ref(false);
// 输入的要添加的股票代码
const inputTsCode = ref("000001.SZ");
const pageParams = reactive({
  page: 1,
  pageSize: 3,
  total:0
})

onMounted(() => {
  // loadRecommendedNews(); // 加载推荐新闻
  // loadSampleStocks(); // 加载虚拟股票数据
  getWatchList()
  getWatchNews()
});

let emptyMessage=ref("请先登录")
watch(()=>store.UserMessage,()=>{
  if(!sessionStorage.getItem("token")){
    emptyMessage.value="请先登录"
    return
  }
  emptyMessage.value="自选股列表为空"
},{deep:true,immediate:true})

// 添加自选股
function addSelect(){
  let watchlist = {}
  watchlist.stockCode = inputTsCode.value
  watchlist.userId = userMessage.value.id
  addWatchlistApi(watchlist).then(res => {
    ElMessage.success('添加成功')
    dialogVisible.value = false
    getWatchList()
  })
}

// 删除我的某一条自选股
function removeWatchlist(id){
  let stockCode=null
  let stockName=null
  for (let i = 0; i < stocks.value.length; i++) {
    if(stocks.value[i].id === id){
      stockCode=stocks.value[i].ts_code
      stockName=stocks.value[i].name
      break;
    }
  }
  ElMessageBox.confirm(
      `${stockCode+" "+stockName+" "}将会被删除，是否继续？`,
      'Warning',
      {
        confirmButtonText: '继续删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        removeWatchlistApi(id).then(res => {
          console.log("resp = ",res);
          ElMessage.success('删除成功')
          getWatchList()
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除操作',
        })
      })
}

// 格式化日期
function formatDate(dateString) {
  let year = dateString.slice(0, 4);
  let month = dateString.slice(4, 6);
  let day = dateString.slice(6, 8);
  return `${year}/${parseInt(month)}/${parseInt(day)}`;
}


// 获取自选股相关新闻
const getWatchNews = () => {

  getSelectNewsApi(pageParams.page,pageParams.pageSize).then((res)=>{
    pageParams.total = res.total
    selectNews.value = res.records
  })
}


// 格式化增长比例
function formatRatio(value) {
  let ratio = value.ratio;
  if (ratio > 0) {
    return `+${ratio.toFixed(2)}%`;
  } else if (ratio < 0) {
    return `${ratio.toFixed(2)}%`;
  } else {
    return "0.00%";
  }
}

// 格式化成交量
function formatVolume(item) {
  let value = item.volume;
  if (value >= 100000000) {
    return (value / 100000000).toFixed(2) + '亿';
  } else if (value >= 10000000) {
    return (value / 10000000).toFixed(2) + '千万';
  } else if (value >= 1000000) {
    return (value / 1000000).toFixed(2) + '百万';
  } else if (value >= 10000) {
    return (value / 10000).toFixed(2) + '万';
  } else {
    return value;
  }
}

// 根据股票名称或者代码对股票进行筛选
const filteredStocks = computed(() => {
  const search = searchQuery.value.toLowerCase();
  return stocks.value.filter(stock => {
    return stock.name.toLowerCase().includes(search) || stock.ts_code.toLowerCase().includes(search);
  });
});

// 获取用户自选股票列表
function getWatchList() {
  if (userMessage.value === null ) {
    ElMessage.error('请先登录')
    return;
  }
  let param = { userId: userMessage.value.id }
  getWatchlistApi(param).then(res => {
    // 清空原有数据
    stocks.value = [];
    let records = res.records;
    let stockCodes = [];
    if (records && records.length > 0) {
      for (let i = 0; i < records.length; i++) {
        let stock = {}
        stock.stockId = records[i].stockId
        stock.id = records[i].id
        stock.name = records[i].stockName
        stock.ts_code = records[i].stockCode
        stockCodes.push(records[i].stockCode)
        stocks.value.push(stock);
      }
    }
    getStockRealData();
  });
}

// 获取自选股实时数据
const getStockRealData = () => {
  for (let i = 0; i < stocks.value.length; i++) {
    let stock = stocks.value[i];
    getStockRealDataApi(stock.ts_code).then(res => {
      let data = res.data;
      stock.date = data.t;
      stock.high = data.h;
      stock.low = data.l;
      stock.open = data.o;
      stock.pre_close = data.yc;
      stock.price = data.p;
      stock.volume = data.v;
      stock.ratio = data.pc;
      stock.status = data.pc > 0 ? 'up' : 'down';

      // 获取股票新闻
      listThreeNewsApi(stock.id).then(res=>{
        stock.news = res
      })
      // console.log("stock", stock);
    })
  }
}

// 添加自选股
function addMyStock() {
  if (!sessionStorage.getItem("token")) {
    ElMessage.error('请先登录')
    return;
  }
  dialogVisible.value = true;
}

// 判断是否已经点开过这条新闻，点开过的新闻标题会变灰
function getHasCheckedJournalism(id) {
  let data=JSON.parse(localStorage.getItem('hasCheckedJournalism')) || [];
  return data.indexOf(id.toString()) !== -1;
}


// 跳转到新闻详情页
function ToJournalismPage(id){
  Router.push({
    path:'/journalismContent',
    query:{jourId:id}
  })
}

// 跳转到股票详情页面
function ToStockMessagePage(row) {
  console.log(row)
  router.push({
    path: "/stockDetail",
    query: {
      stockId: row.stockId
    }
  })
}

// 表格行样式
const rowStyle = () => {
  return {
    cursor: 'pointer',
  }
}

</script>

<style scoped>
.stock-management-container,
.newslist-container {
  width: 80%;
  /* 设置宽度为80% */
  max-width: 1200px;
  /* 设置最大宽度为1200px（可选） */
  margin: 20px auto;
  /* 垂直居中 */
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  /* 添加阴影效果 */
}

.header-title {
  font-size: 28px;
  /* 设置字体大小 */
  color: #333;
  /* 字体颜色 */
  margin-bottom: 15px;
  /* 下边距 */
  font-weight: bold;
  /* 字体加粗 */
}

.filter {
  margin-bottom: 20px;
}

.el-table th,
.el-table td {
  font-weight: bold;
  /* 表头和单元格字体加粗 */
}


.newslist {
  /*background-color: #1890ff;*/
  padding: 10px;
  margin-bottom: 50px;
  width: 75%;
}

.newsli {
  padding-bottom: 6px;
  border-bottom: 1px solid #d1a9a9;
  margin-bottom: 9px;
  cursor: pointer;
}

.news_title {
  margin: 0;
  margin-left: 17px;
}

.news_time {
  font-size: 13px;
  color: #939393;
  line-height: 26px;
  position: absolute;
  right: 16px;
}

.newsTop {
  display: flex;
  position: relative;
  margin-bottom: 11px;
}

.badge {
  display: inline-block;
  background-color: rgba(0, 128, 0, 0.78);
  color: white;
  padding: 5px 9px;
  width: 25px;
  border-radius: 8px;
  font-size: 11px;
  text-align: center;
  box-shadow: 0 2px 5px rgb(0 0 0 / 20%);
  height: 16px;
}

.goodge{
  display: inline-block;
  background-color: red;
  color: white;
  padding: 5px 9px;
  width: 25px;
  border-radius: 8px;
  font-size: 11px;
  text-align: center;
  box-shadow: 0 2px 5px rgb(0 0 0 / 20%);
  height: 16px;
}
.unknownge{
  display: inline-block;
  background-color: #808080;
  color: white;
  padding: 5px 9px;
  width: 25px;
  border-radius: 8px;
  font-size: 11px;
  text-align: center;
  box-shadow: 0 2px 5px rgb(0 0 0 / 20%);
  height: 16px;
}

.news_content {
  margin-bottom: 9px;
  width: 755px;
  padding-left: 56px;
  font-size: 22px;
}

.news_img {
  width: 250px;
  height: 150px;
  margin-left: 25px;
}

.relatedStockArea {
  display: flex;
  width: 866px;
}

.relatedStock {
  margin-left: 6px;
  font-size: 12px;
  color: #686868;
  margin-top: 5px;
}
.newsMessage{
  display: flex;
  color: #898888;
  margin-left: 17px;
  margin-top: 5px;
  font-size: 13px;
}
.newsMessage div{
  margin-left: 85px;
}
</style>
